package msg.visitors;

import msg.*;

import org.w3c.dom.*;

import common.interfaces.IMessageVisitor;

/**
 * Creates an XML element of the message
 * 
 * @author Gal Lalouche
 */
public class MessageToXML implements IMessageVisitor<Element> {
	private final Document	doc;
	
	/**
	 * Creates a new instance
	 * 
	 * @param doc The document to create the element out of
	 */
	public MessageToXML(Document doc) {
		if (doc == null) {
			throw new IllegalArgumentException("doc is null");
		}
		this.doc = doc;
	}
	
	private Element appendToElement(Element msgElement, String string) {
		Element temp = doc.createElement(string);
		msgElement.appendChild(temp);
		return temp;
	}
	
	@Override
	public Element visit(Message message) {
		Element msgElement = doc.createElement("MESSAGE");
		msgElement.setAttribute("id", message.getId().toString());
		Element location = appendToElement(msgElement, "LOCATION");
		location.setAttribute("lat", message.getLocation().getLatitude() + "");
		location.setAttribute("long", message.getLocation().getLongitude() + "");
		Element content = appendToElement(msgElement, "CONTENT");
		content.setTextContent(message.getContent());
		Element poster = appendToElement(msgElement, "POSTER_ID");
		poster.setAttribute("id", message.getPoster().getId());
		Element time = appendToElement(msgElement, "TIME_IN_MILIS");
		time.setAttribute("time", message.getTime() + "");
		if (message.getLocation().getAddress() != null) {
			Element address = appendToElement(msgElement, "ADDRESS");
			address.setAttribute("address", message.getLocation().getAddress());
		}
		return msgElement;
	}
	
	@Override
	public Element visit(EventMessage event) {
		Element eventElement = doc.createElement("EVENT");
		Element msgElement = visit((Message)event);
		eventElement.appendChild(msgElement);
		Element cap = appendToElement(eventElement, "CAPACITY");
		cap.setAttribute("number", event.getCapacity() + "");
		return eventElement;
	}
}
